//
//  XDUserAccountViewModel.swift
//  weibo
//
//  Created by lucy on 2016/10/25.
//  Copyright © 2016年 com.huashengHuaSheng. All rights reserved.
//

import UIKit

//自定义类
class XDUserAccountViewModel {
    
    static let shareTools : XDUserAccountViewModel = XDUserAccountViewModel()
    var userAccountModel : XDUserAccountModel?
    //路径
    let path = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.db")
    
    var isLogin : Bool{
        
    
        return accessToken != nil
    }
    
    
    
    //访问令牌
    var accessToken: String?{
    
        if userAccountModel?.expires_Date?.compare(Date()) == ComparisonResult.orderedDescending{
        
            return userAccountModel?.access_token
        }else{
            return nil
        
        }
    
    }
    
    init() {
        userAccountModel = getUserAccountModelInfo()
    }
}


//归档和解档方法
extension XDUserAccountViewModel{

    //保存用户信息
    func saveUserAccount(model: XDUserAccountModel){
        userAccountModel = model
        NSKeyedArchiver.archiveRootObject(model, toFile: path)
    }
    
    //获取用户信息
   fileprivate func getUserAccountModelInfo()->XDUserAccountModel?{
    
        let result = NSKeyedUnarchiver.unarchiveObject(withFile: path) as?XDUserAccountModel
    return result

    }
}


//MARK-请求数据
extension XDUserAccountViewModel{

    //获取token
    func getUserAccount(code: String, finish: @escaping (Bool)->()){
    
        XDNetworkTool.shareTool.oauthloadUserAccount(code: code, success: { (response) in
            
            guard let res = response as?[String:Any] else{
                finish(false)
                return
            }
            
            let userAccountModel = XDUserAccountModel.yy_model(withJSON: res)
            guard let model = userAccountModel else{
                finish(false)
                return
            }
            self.getUserInfo(model: model, finish: finish)
            
            }) { (error) in
                 finish(false)
                print("请求失败",error)
        }

    }
    
    func getUserInfo(model:XDUserAccountModel ,finish:@escaping (Bool)->()){
    
        XDNetworkTool.shareTool.oauthLoadUserInfo(model: model, success: { (response) in
            
            guard let res = response as?[String:Any] else{
            
                finish(false)
                return
            }
            model.screen_name = res["screen_name"] as? String
            model.avatar_large = res["avatar_large"] as? String
            self.saveUserAccount(model: model)
            finish(true)
            }) { (error) in
                finish(false)
                print("请求失败",error)
                
        }

    }
}
















































